package com.hmdp.interceptor;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
将用户存入本地线程以及刷新token的拦截器
 */
public class RefreshInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    //前置，拦截请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");

        //构造访问redis的key
        String key = RedisConstants.LOGIN_USER_KEY + token;

        //判断token是否为空
        if (StrUtil.isBlank(token)){
            //直接放行
            return true;
        }

        //根据token获取redis中的用户（Map类型）
        Map userMap = redisTemplate.opsForHash().entries(key);

        //判断用户是否存在
        if (userMap.isEmpty()){
            response.setStatus(401);
            //直接放行
            return true;
        }

        //将用户数据从Map解析为UserDTO
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        //存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //刷新token有效期
        redisTemplate.expire(key, RedisConstants.LOGIN_USER_TTL, TimeUnit.DAYS);

        //放行
        return true;
    }

    //拦截请求完全处理后，避免内存泄露
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //移除用户
        UserHolder.removeUser();
    }

    public RefreshInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
